package com.css.fxfzcpxx.modules.courseManage.service.impl;

import com.alibaba.druid.util.StringUtils;
import com.css.fxfzcpxx.base.attachment.entity.AttachmentInfoEntity;
import com.css.fxfzcpxx.base.attachment.repository.AttachmentInfoRepository;
import com.css.fxfzcpxx.constants.YNEnum;
import com.css.fxfzcpxx.modules.certificateManage.entity.CertificateRule;
import com.css.fxfzcpxx.modules.certificateManage.repository.CertificateManageRepository;
import com.css.fxfzcpxx.modules.certificateManage.vo.CertificateRuleVo;
import com.css.fxfzcpxx.modules.courseManage.entity.CourseManage;
import com.css.fxfzcpxx.modules.courseManage.entity.TestPaperTemplate;
import com.css.fxfzcpxx.modules.courseManage.entity.TestPaperTemplateRule;
import com.css.fxfzcpxx.modules.courseManage.param.CourseManageServiceParam;
import com.css.fxfzcpxx.modules.courseManage.param.CourseManageParam;
import com.css.fxfzcpxx.modules.courseManage.repository.CourseManageRepository;
import com.css.fxfzcpxx.modules.courseManage.service.CourseManageService;
import com.css.fxfzcpxx.modules.courseManage.vo.*;
import com.css.fxfzcpxx.modules.questionData.entity.UserTestHistory;
import com.css.fxfzcpxx.modules.questionData.vo.FractionalCurveListVO;
import com.css.fxfzcpxx.modules.questionData.vo.FractionalCurveVO;
import com.css.fxfzcpxx.modules.questionData.vo.UserTestHistoryVO;
import com.css.fxfzcpxx.util.EasyPoiExcelUtil;
import com.css.fxfzcpxx.util.PlatformDateUtils;
import com.css.fxfzcpxx.util.PlatformObjectUtils;
import com.css.fxfzcpxx.web.PlatformSessionContext;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.sql.Timestamp;
import java.util.*;

/**
 * @Author: zhangSongRui
 * @CreateTime: 2023/03/08
 * @Description: 在线课堂管理Service
 */
@Service
public class CourseManageServiceImpl implements CourseManageService {
    @Resource
    private CourseManageRepository courseManageRepository;

    @Resource
    private AttachmentInfoRepository attachmentInfoRepository;

    @Resource
    CertificateManageRepository certificateManageRepository;


    //分页
    @Override
    public Map<String, Object> getPage(int curPage, int pageSize, CourseManageParam param) {
        return courseManageRepository.getPage(curPage, pageSize, param);
    }

    //新增
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void save(CourseManageServiceParam param) {
        //判断默认图片是否存在如果不存在则添加
        if (param.getCourseManage().getCover().equals("123")) {
            AttachmentInfoEntity attach = attachmentInfoRepository.getAttach("123");
            //如果没有则写入
            if (attach == null) {
                AttachmentInfoEntity attachmentInfoEntity = new AttachmentInfoEntity();
                attachmentInfoEntity.setAttachId("123");
                attachmentInfoEntity.setAttachName("默认在线课堂图片.jpg");
                attachmentInfoEntity.setAttachPath("/default/默认在线课堂图片.jpg");
                attachmentInfoEntity.setIsCompleted("1");
                attachmentInfoEntity.setIsValid("1");
                attachmentInfoEntity.setFileDirId("D:\\static");
                attachmentInfoRepository.save(attachmentInfoEntity);
            }
        }
        String userID = PlatformSessionContext.getUserID();
        Timestamp createTime = PlatformDateUtils.getCurrentTimestamp();
        param.getCourseManage().setId(UUID.randomUUID().toString().replaceAll("-", ""));
        param.getCourseManage().setCreateUser(userID);
        param.getCourseManage().setDelFlag(YNEnum.N.toString());
        param.getCourseManage().setCreateTime(createTime);
        //如果有随堂练习
        if (param.getCourseManage().getExercise().equals("0")) {
            param.getTestPaperTemplate().setId(UUID.randomUUID().toString().replaceAll("-", ""));
            param.getTestPaperTemplate().setCreateUser(userID);
            param.getTestPaperTemplate().setDelFlag(YNEnum.N.toString());
            param.getTestPaperTemplate().setCreateTime(createTime);
            //保存模板
            courseManageRepository.saveTestPaperTemplate(param.getTestPaperTemplate());
            //试卷模板id
            String templateId = param.getTestPaperTemplate().getId();
            param.getCourseManage().setExerciseId(templateId);
            //保存模板规则
            for (TestPaperTemplateRule testPaperTemplateRule : param.getList()) {
                testPaperTemplateRule.setId(UUID.randomUUID().toString().replaceAll("-", ""));
                //模板id
                testPaperTemplateRule.setTemplateId(templateId);
                testPaperTemplateRule.setCreateUser(userID);
                testPaperTemplateRule.setDelFlag(YNEnum.N.toString());
                testPaperTemplateRule.setCreateTime(createTime);
                courseManageRepository.saveTestPaperTemplateRule(testPaperTemplateRule);
            }
        }
        //保存在线课堂
        courseManageRepository.save(param.getCourseManage());
    }

    //更改发布状态
    @Override
    public void updateReleaseStatusById(List<String> id, String toString) {
        courseManageRepository.updateReleaseStatusById(id,  new Date(),toString);
    }

    //根据ids批量删除在线课堂,考试模板,模板规则
    @Override
    public void delete(String ids) {
        List<String> list = courseManageRepository.queryExerciseId(ids);
        courseManageRepository.delete(Arrays.asList(ids.split(",")));
        courseManageRepository.deleteTemplate(list);
        courseManageRepository.deleteTemplateRule(list);
    }

    //目录下载
    @Override
    public void exportData(HttpServletResponse response, String ids) {
        List<CourseManage> list = courseManageRepository.queryByParam(Arrays.asList(ids.split(",")));
        EasyPoiExcelUtil.exportExcel(list, "在线课堂目录", "sheet1", CourseManage.class, "在线课堂目录", response);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateById(CourseManageServiceParam param) {
        String userID = PlatformSessionContext.getUserID();
        Timestamp createTime = PlatformDateUtils.getCurrentTimestamp();
        param.getCourseManage().setUpdateUser(userID);
        param.getCourseManage().setUpdateTime(createTime);
        //如果有随堂练习
        if (param.getCourseManage().getExercise().equals("0")) {
            //批量删除之前的随堂练习模板和模板规则   真删
            courseManageRepository.deleteTemplateAndRule(param.getTestPaperTemplate().getId());
            param.getTestPaperTemplate().setId(UUID.randomUUID().toString().replaceAll("-", ""));
            param.getTestPaperTemplate().setCreateUser(userID);
            param.getTestPaperTemplate().setCreateTime(createTime);
            param.getTestPaperTemplate().setDelFlag(YNEnum.N.toString());
            //保存模板
            courseManageRepository.saveTestPaperTemplate(param.getTestPaperTemplate());
            //试卷模板id
            String templateId = param.getTestPaperTemplate().getId();
            //写入新的试卷模板到在线课堂
            param.getCourseManage().setExerciseId(templateId);
            //保存模板规则
            for (TestPaperTemplateRule testPaperTemplateRule : param.getList()) {
                testPaperTemplateRule.setId(UUID.randomUUID().toString().replaceAll("-", ""));
                //模板id
                testPaperTemplateRule.setTemplateId(templateId);
                testPaperTemplateRule.setCreateUser(userID);
                testPaperTemplateRule.setCreateTime(createTime);
                testPaperTemplateRule.setDelFlag(YNEnum.N.toString());
                courseManageRepository.saveTestPaperTemplateRule(testPaperTemplateRule);
            }
        } else {
            //如果试卷模板id不为null
            if (!StringUtils.isEmpty(param.getCourseManage().getExerciseId())) {
                ArrayList<String> list = new ArrayList<>();
                list.add(param.getCourseManage().getExerciseId());
                //批量删除之前的随堂练习
                courseManageRepository.deleteTemplate(list);
                courseManageRepository.deleteTemplateRule(list);
                //如果没有随堂训练试卷模板id为null
                param.getCourseManage().setExerciseId(null);
            }
        }
        courseManageRepository.updateById(param.getCourseManage());
    }

    //根据id查询
    @Override
    public CourseManageServiceParamVO findById(String id) {
        CourseManageServiceParamVO courseManageServiceParamVO = new CourseManageServiceParamVO();
        CourseManage courseManage = courseManageRepository.findById(id);
        if (!StringUtils.isEmpty(courseManage.getExerciseId())) {
            TestPaperTemplate testPaperTemplate = courseManageRepository.findTemplateById(courseManage.getExerciseId());
            List<TestPaperTemplateRule> list = courseManageRepository.findTemplateRuleById(courseManage.getExerciseId());
            //获取该类型下的总题数和各类型题数
            List<TestPaperTemplateRuleVO> arrayList = new ArrayList<>();
            for (TestPaperTemplateRule testPaperTemplateRule : list) {
                List<TypeManageNumVO> typeNum = courseManageRepository.getTypeNumByTypeId(testPaperTemplateRule.getTypeId());
                TestPaperTemplateRuleVO testPaperTemplateRuleVO = new TestPaperTemplateRuleVO();
                for (TypeManageNumVO typeManageNumVO : typeNum) {
                    //题库中单选题数量
                    if (typeManageNumVO.getQuestionType().equals("0")){
                        testPaperTemplateRuleVO.setSingleOptionNum(typeManageNumVO.getNum());
                    }
                    //题库中多选题数量
                    if (typeManageNumVO.getQuestionType().equals("1")){
                        testPaperTemplateRuleVO.setMultipleSelectionNum(typeManageNumVO.getNum());
                    }
                    //题库种判断体数量
                    if (typeManageNumVO.getQuestionType().equals("2")){
                        testPaperTemplateRuleVO.setJudgmentNum(typeManageNumVO.getNum());
                    }
                    //写入类别名称
                    testPaperTemplateRuleVO.setTypeName(typeManageNumVO.getTypeName());
                }
                //复制
                BeanUtils.copyProperties(testPaperTemplateRule, testPaperTemplateRuleVO);
                arrayList.add(testPaperTemplateRuleVO);
            }
            courseManageServiceParamVO.setTestPaperTemplate(testPaperTemplate);
            courseManageServiceParamVO.setList(arrayList);
        }
        CourseManageVO courseManageVO = new CourseManageVO();
        //复制
        BeanUtils.copyProperties(courseManage, courseManageVO);
        AttachmentInfoEntity attach = attachmentInfoRepository.getAttach(courseManage.getCourseFile());

        if(PlatformObjectUtils.isNotEmpty(courseManage.getCover())){
            AttachmentInfoEntity coverAttach = attachmentInfoRepository.getAttach(courseManage.getCover());
            courseManageVO.setCoverAttach(coverAttach);
        }
        courseManageVO.setAttach(attach);
        courseManageServiceParamVO.setCourseManageVO(courseManageVO);
        return courseManageServiceParamVO;
    }

    @Override
    public List<TypeManageVO> getTypeNum(String typeName) {
        List<TypeManageNumVO> typeNum = courseManageRepository.getTypeNum(typeName);
        ArrayList<TypeManageVO> list = new ArrayList<>();
        for (int i = typeNum.size(); i > 0; i--) {
            TypeManageNumVO typeManageNumVO = typeNum.get(0);
            String typeId = typeManageNumVO.getId();
            TypeManageVO typeManageVO = new TypeManageVO();
            typeManageVO.setId(typeManageNumVO.getId());
            typeManageVO.setTypeName(typeManageNumVO.getTypeName());
            typeManageVO.setTypePlate(typeManageNumVO.getTypeName());
            for (int j = 0; j < typeNum.size(); j++) {
                TypeManageNumVO manageNumVO = typeNum.get(j);
                if (manageNumVO.getId().equals(typeId)) {
                    //没有题目类型则跳过
                    if (null == manageNumVO.getQuestionType()) {
                        typeNum.remove(j);
                        j--;
                        i--;
                        continue;
                    }
                    if (manageNumVO.getQuestionType().equals("0")) {
                        typeManageVO.setSingleOptionNum(manageNumVO.getNum());
                    } else if (manageNumVO.getQuestionType().equals("1")) {
                        typeManageVO.setMultipleSelectionNum(manageNumVO.getNum());
                    } else if (manageNumVO.getQuestionType().equals("2")) {
                        typeManageVO.setJudgmentNum(manageNumVO.getNum());
                    }
                    typeNum.remove(j);
                    j--;
                    i--;
                }
            }
            list.add(typeManageVO);
            i++;
        }
        return list;
    }

    //根据试卷id查询历史试卷
    @Override
    public GetHistoryTestVO getHistoryTest(String id) {
        List<HistoryTestVO> historyTest = courseManageRepository.getHistoryTest(id);
        GetHistoryTestVO getHistoryTestVO = new GetHistoryTestVO();
        //单选
        ArrayList<HistoryTestVO> singleChoiceList = new ArrayList<>();
        //多选
        ArrayList<HistoryTestVO> multipleSelectionList = new ArrayList<>();
        //判断
        ArrayList<HistoryTestVO> judgmentList = new ArrayList<>();
        for (HistoryTestVO historyTestVO : historyTest) {
            //单选
            if (historyTestVO.getQuestionType().equals("0")) {
                singleChoiceList.add(historyTestVO);
            }
            //多选
            if (historyTestVO.getQuestionType().equals("1")) {
                multipleSelectionList.add(historyTestVO);
            }
            //判断
            if (historyTestVO.getQuestionType().equals("2")) {
                judgmentList.add(historyTestVO);
            }
        }
        getHistoryTestVO.setSingleChoice(singleChoiceList);
        getHistoryTestVO.setMultipleSelection(multipleSelectionList);
        getHistoryTestVO.setJudgment(judgmentList);
        return getHistoryTestVO;
    }

    //滚动分页
    @Override
    public Map<String, Object> getOnlinePage(int curPage, int pageSize) {
        String userID = PlatformSessionContext.getUserID();
        Map<String, Object> onlinePage = courseManageRepository.getOnlinePage(curPage, pageSize, userID);
        List<OnlineCourseVO> list = (List<OnlineCourseVO>) onlinePage.get("rows");
        for (OnlineCourseVO onlineCourseVO : list) {
            if (onlineCourseVO.getDownload().equals("0")) {
                AttachmentInfoEntity attach = attachmentInfoRepository.getAttach(onlineCourseVO.getCourseFile());
                onlineCourseVO.setAttachmentInfoEntity(attach);
            }
        }
        onlinePage.put("rows", list);
        return onlinePage;
    }

    @Override
    public List<UserTestHistory> getTestListByCourseId(String courseId) {
        String userID = PlatformSessionContext.getUserID();
        return courseManageRepository.getTestListByCourseId(courseId, userID);
    }

    //查询排行榜
    @Override
    public List<UserTestHistoryVO> getRanking() {
        return courseManageRepository.getRanking();
    }

    @Override
    public FractionalCurveListVO getFractionalCurve() {
        List<FractionalCurveVO> fractionalCurve = courseManageRepository.getFractionalCurve();
        String a = courseManageRepository.getUserScore(PlatformSessionContext.getUserID());
        //如果用户没考过试给他个零
        if (a == null) {
            a = "0";
        }
        ArrayList<String> listY = new ArrayList<>();
        String numX = "0";
        String yNum = "0";
        //最大人数
        int maxY = 0;
        int index = 0;
        boolean boo = true;
        FractionalCurveListVO fractionalCurveListVO = new FractionalCurveListVO();
        for (int i = 0; i < 101; i++) {
            //如果x轴等于就写入人数
            if (boo) {
                if (fractionalCurve.get(index).getScoreAvg().equals(String.valueOf(i))) {
                    //写入最大人数
                    if (Integer.parseInt(fractionalCurve.get(index).getNum()) > maxY) {
                        maxY = Integer.parseInt(fractionalCurve.get(index).getNum());
                    }
                    //写入用户当前位置,如果他考过试
                    if (fractionalCurve.get(index).getScoreAvg().equals(a)) {
                        numX = a;
                        yNum = fractionalCurve.get(index).getNum();
                    }
                    //写入该分数对应的人数
                    listY.add(fractionalCurve.get(index).getNum());
                    index++;
                    //在索引指向最后一位时关闭
                    if (index >= fractionalCurve.size()) {
                        boo = false;
                    }
                } else {
                    listY.add("0");
                }
            } else {
                listY.add("0");
            }
        }

        //获取及格线与优秀线
        //获取证书规则
        List<CertificateRuleVo> certificateList = certificateManageRepository.queryRule();
        fractionalCurveListVO.setY(listY);
        fractionalCurveListVO.setXNum(numX);
        fractionalCurveListVO.setYNum(yNum);
        fractionalCurveListVO.setYMax(maxY);
        fractionalCurveListVO.setXQualified(certificateList.get(1).getGreaterThan());
        fractionalCurveListVO.setXExcellent(certificateList.get(0).getGreaterThan());
        return fractionalCurveListVO;
    }

}
